cc.Class({
    extends: cc.Component,

    properties: {
        rankItem: cc.Prefab,
        rankingScrollView: cc.Node,
        rankContentNode: cc.Node,

        nearRankItem: cc.Prefab,
        nearScrollView: cc.Node,
        nearContentNode: cc.Node,
        nextNode: cc.Node,
        nextSprite: cc.Sprite,

    },

    start: function () {
        if (typeof wx != 'undefined') {
            var self = this
            wx.onMessage(data => {
                if (data.messageType == 1) {
                    self.rankContentNode.removeAllChildren();
                    self.nearContentNode.removeAllChildren();
                }
                else if (data.messageType == 2) {  //提交最高分
                    self.submitScore(data.MAIN_MENU_NUM, data.score);
                }
                else if (data.messageType == 3) {
                    self.fetchFriendData(data.MAIN_MENU_NUM);
                }
                else if (data.messageType == 4) {
                    self.fetchNearData(data.MAIN_MENU_NUM);
                }
                else if (data.messageType == 5) {
                    self.showNextFriendList(data.MAIN_MENU_NUM);
                }
            })
        }

    },


    showNextFriendList: function (MAIN_MENU_NUM) {
        this.nearScrollView.active = false;
        this.rankingScrollView.active = false;
        this.nextNode.active = true;
        wx.getUserInfo({
            openIdList: ['selfOpenId'],
            success: (userRes) => {
                console.log('wx.getUserInfo success', userRes.data)
                let userData = userRes.data[0];
                //取出所有好友数据
                wx.getFriendCloudStorage({
                    keyList: [MAIN_MENU_NUM],
                    success: res => {
                        console.log("wx.getFriendCloudStorage success", res);
                        let data = res.data;
                        data.sort((a, b) => {
                            if (a.KVDataList.length == 0 && b.KVDataList.length == 0) {
                                return 0;
                            }
                            if (a.KVDataList.length == 0) {
                                return 1;
                            }
                            if (b.KVDataList.length == 0) {
                                return -1;
                            }
                            return b.KVDataList[0].value - a.KVDataList[0].value;
                        });
                        for (let i = 0; i < data.length; i++) {
                            var playerInfo = data[i];
                            var isSelf = false;
                            if (playerInfo.avatarUrl == userData.avatarUrl) {
                                //自己
                                if (i == 0) {
                                    isSelf = true;
                                    this.showNextUI(data[0], isSelf);
                                }
                                else {
                                    this.showNextUI(data[i - 1], isSelf);
                                }
                            }
                            // var item = cc.instantiate(self.rankItem);
                            // item.getComponent('rankItem').init(i, playerInfo, isSelf);
                            // item.parent = self.rankContentNode;
                        }
                    },
                    fail: res => {
                        console.log("wx.getFriendCloudStorage fail", res);
                    },
                });
            },
            fail: (res) => {
                console.log('wx.getUserInfo fail', res)
                //reject(res)
            }
        })

    },


    showNextUI: function (data, isSelf) {
        this.createImage(data.avatarUrl);
        this.nextNode.getChildByName('name').string = data.nickname;
        if (isSelf) {
            this.nextNode.getChildByName('nextLabel').getComponent(cc.Label).string = "无人可挡";
        }
        else {
            this.nextNode.getChildByName('nextLabel').getComponent(cc.Label).string = "下一个即将超过";
        }
        this.nextNode.getChildByName('score').getComponent(cc.Label).string = data.KVDataList.length != 0 ? data.KVDataList[0].value : 0;

    },

    submitScore(MAIN_MENU_NUM, score) { //提交得分
        console.log('sub submitScore')
        if (typeof wx != 'undefined') {
            wx.getUserCloudStorage({
                // 以key/value形式存储
                keyList: [MAIN_MENU_NUM],
                success: function (getres) {
                    console.log('getUserCloudStorage', 'success', getres)
                    if (getres.KVDataList.length != 0) {
                        if (getres.KVDataList[0].value > score) {
                            return;
                        }
                    }
                    // 对用户托管数据进行写数据操作
                    window.wx.setUserCloudStorage({
                        KVDataList: [{ key: MAIN_MENU_NUM, value: "" + score }],
                        success: function (res) {
                            console.log('setUserCloudStorage', 'success', res)
                        },
                        fail: function (res) {
                            console.log('setUserCloudStorage', 'fail')
                        },
                        complete: function (res) {
                            console.log('setUserCloudStorage', 'ok')
                        }
                    });
                },
                fail: function (res) {
                    console.log('getUserCloudStorage', 'fail')
                },
                complete: function (res) {
                    console.log('getUserCloudStorage', 'ok')
                }
            });
        } else {
            cc.log("提交得分:" + MAIN_MENU_NUM + " : " + score)
        }
    },

    fetchFriendData(MAIN_MENU_NUM) {
        console.log("sub fetchFriendData");
        this.nearScrollView.active = false;
        this.nearContentNode.removeAllChildren();
        this.rankingScrollView.active = true;
        this.rankingScrollView.getComponent(cc.ScrollView).scrollToTop();
        this.rankContentNode.removeAllChildren();
        var self = this;

        wx.getUserInfo({
            openIdList: ['selfOpenId'],
            success: (userRes) => {
                console.log('wx.getUserInfo success', userRes.data)
                let userData = userRes.data[0];
                //取出所有好友数据
                wx.getFriendCloudStorage({
                    keyList: [MAIN_MENU_NUM],
                    success: res => {
                        console.log("wx.getFriendCloudStorage success", res);
                        let data = res.data;
                        data.sort((a, b) => {
                            if (a.KVDataList.length == 0 && b.KVDataList.length == 0) {
                                return 0;
                            }
                            if (a.KVDataList.length == 0) {
                                return 1;
                            }
                            if (b.KVDataList.length == 0) {
                                return -1;
                            }
                            return b.KVDataList[0].value - a.KVDataList[0].value;
                        });
                        for (let i = 0; i < data.length; i++) {
                            var playerInfo = data[i];
                            var isSelf = false;
                            if (playerInfo.avatarUrl == userData.avatarUrl) {
                                //自己
                                isSelf = true;
                            }
                            var item = cc.instantiate(self.rankItem);
                            item.getComponent('rankItem').init(i, playerInfo, isSelf);
                            item.parent = self.rankContentNode;
                        }
                    },
                    fail: res => {
                        console.log("wx.getFriendCloudStorage fail", res);
                    },
                });
            },
            fail: (res) => {
                console.log('wx.getUserInfo fail', res)
                //reject(res)
            }
        })

    },

    fetchNearData(MAIN_MENU_NUM) {
        this.nearScrollView.active = true;
        this.nearContentNode.removeAllChildren();
        this.rankingScrollView.active = false;
        this.rankContentNode.removeAllChildren();
        console.log("sub fetchNearData");
        var self = this;
        //先获取用户信息
        console.log('get UserInfo first');
        wx.getUserInfo({
            openIdList: ['selfOpenId'],
            success: (userRes) => {
                console.log('wx.getUserInfo success', userRes.data)
                let userData = userRes.data[0];
                //取出所有好友数据
                wx.getFriendCloudStorage({
                    keyList: [MAIN_MENU_NUM],
                    success: res => {
                        cc.log("wx.getFriendCloudStorage success", res);
                        let data = res.data;
                        data.sort((a, b) => {
                            if (a.KVDataList.length == 0 && b.KVDataList.length == 0) {
                                return 0;
                            }
                            if (a.KVDataList.length == 0) {
                                return 1;
                            }
                            if (b.KVDataList.length == 0) {
                                return -1;
                            }
                            return b.KVDataList[0].value - a.KVDataList[0].value;
                        });
                        var threeData = []
                        for (let i = 0; i < data.length; i++) {
                            if (data[i].avatarUrl == userData.avatarUrl) {
                                if ((i + 1) > data.length) {  //自己是最后一个
                                    console.log("last");
                                    if (i - 2 >= 0) {
                                        threeData.push(data[i - 2]);
                                    }
                                    if (i - 1 >= 0) {
                                        threeData.push(data[i - 1]);
                                    }
                                    threeData.push(data[i]);
                                }
                                if ((i - 1) < 0) { //自己在最前面  （自己是第一）
                                    console.log("first");
                                    threeData.push(data[i]);
                                    if (i + 1 < data.length) {
                                        threeData.push(data[i + 1]);
                                    }
                                    if (i + 2 < data.length) {
                                        threeData.push(data[i + 2]);
                                    }
                                }
                                else {  //自己在中间
                                    console.log("mid");
                                    if (i - 1 >= 0) {
                                        threeData.push(data[i - 1]);
                                    }
                                    threeData.push(data[i]);
                                    if (i + 1 < data.length) {
                                        threeData.push(data[i + 1]);
                                    }
                                }
                                break;
                            }
                        }
                        console.log("threeData->", threeData);
                        for (let i = 0; i < threeData.length; i++) {
                            var playerInfo = threeData[i];
                            var item = cc.instantiate(self.nearRankItem);
                            item.getComponent('rankItem').init(i, playerInfo);
                            item.parent = self.nearContentNode;
                        }
                    },
                    fail: res => {
                        console.log("wx.getFriendCloudStorage fail", res);
                    },
                });
            },
            fail: (res) => {
                console.log('wx.getUserInfo fail', res)
                //reject(res)
            }
        });
    },

    createImage(avatarUrl) {
        if (CC_WECHATGAME) {
            try {
                let image = wx.createImage();
                image.onload = () => {
                    try {
                        let texture = new cc.Texture2D();
                        texture.initWithElement(image);
                        texture.handleLoadedTexture();
                        this.nextSprite.spriteFrame = new cc.SpriteFrame(texture);
                    } catch (e) {
                        cc.log(e);
                        this.nextSprite.node.active = false;
                    }
                };
                image.src = avatarUrl;
            } catch (e) {
                cc.log(e);
                this.nextSprite.node.active = false;
            }
        } else {
            cc.loader.load({
                url: avatarUrl, type: 'jpg'
            }, (err, texture) => {
                this.nextSprite.spriteFrame = new cc.SpriteFrame(texture);
            });
        }
    }

});
